package com.ahj.openFile;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;

public class OpenFilePlugin implements MethodChannel.MethodCallHandler {
    public static final String CHANNEL = "com.ahj/OpenFilePlugin";
    static MethodChannel channe;
    private Activity activity;

    public OpenFilePlugin(Activity activity) {
        this.activity = activity;
    }

    public static void registerWith(FlutterEngine flutterEngine, Activity activity12) {
        channe = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        OpenFilePlugin plugin = new OpenFilePlugin(activity12);
        channe.setMethodCallHandler(plugin);
    }


    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        try {
            if (methodCall.method.equals("open_file")) {
                String path = methodCall.argument("path");

                File file = new File(path);
                OFUtils ofUtils = OFUtils.newInstance();
                String mimeType = ofUtils.getMIMEType(file);

                // 获取文件Uri 根据系统来区分，7.0一下和7.0以上
                Uri uri = null;
                if (Build.VERSION.SDK_INT >= 24) {
                    //判读版本是否在7.0以上
                    uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", file);
                } else {
                    // 版本在7.0一下
                    uri = Uri.fromFile(file);
                }

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置标记
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(uri, mimeType);//设置类型
                activity.startActivity(intent);
            } else {
                result.notImplemented();
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.success("");
        }
    }
}
